from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base, DeclarativeMeta
from sqlalchemy.orm import sessionmaker
from sqlalchemy_utils import database_exists, create_database

from configs import SQLALCHEMY_DATABASE_URI
import json


engine = create_engine(
    SQLALCHEMY_DATABASE_URI,
    json_serializer=lambda obj: json.dumps(obj, ensure_ascii=False),
    pool_recycle=3600,  # 每小时回收连接（小于MySQL的wait_timeout）
    pool_pre_ping=True,  # 执行前验证连接有效性
)

# engine = create_engine(
#     SQLALCHEMY_DATABASE_URI,
#     pool_recycle=3600,  # 每小时回收连接（小于MySQL的wait_timeout）
#     pool_pre_ping=True,  # 执行前验证连接有效性
#     pool_size=10,       # 根据实际负载调整
#     max_overflow=20,    # 允许临时超出pool_size的连接数
#     pool_timeout=30,    # 获取连接超时时间（秒）
#     json_serializer=lambda obj: json.dumps(obj, ensure_ascii=False) # 序列化
# )

# engine = create_engine(
#     SQLALCHEMY_DATABASE_URI,
#     pool_pre_ping=True,  # 关键参数：自动验证连接
#     pool_recycle=1800,   # 30分钟回收连接（小于MySQL的wait_timeout）
#     pool_size=10,
#     max_overflow=20,
#     connect_args={
#         "connect_timeout": 5,  # 连接超时时间
#         "read_timeout": 30,    # 读操作超时
#         "write_timeout": 30    # 写操作超时
#     },
#     json_serializer=lambda obj: json.dumps(obj, ensure_ascii=False)
# )

if not database_exists(engine.url):
    create_database(engine.url)

SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)

Base: DeclarativeMeta = declarative_base()
